﻿using System;
using System.Linq;
using System.Linq.Expressions;
using SBACN.WebSite.Cache;
using SBACN.WebSite.Code;
using SBACN.WebSite.Models;

namespace SBACN.WebSite.Admin.AboutGuild
{
	public partial class MemberEdit : BasePage
	{

		/// <summary>
		/// 查看新闻的系统字典类型
		/// </summary>
		public string MapCode
		{
			get
			{
				//if (ViewState["SystemType"] == null)
				//    return "00010005";//要闻导读，默认值
				//else
				//    return ViewState["SystemType"].ToString();
				return this.SystemCode;
			}
			private set
			{
				ViewState["SystemType"] = this.SystemCode;
			}
		}
		protected string Url { get; set; }
		protected string ConTitle { get; set; }
		protected void Page_Load(object sender, EventArgs e)
		{

			if (!AdminBasePage.CheckCodeRight(AdminBasePage.AdminInfo, MapCode))
			{
				AdminBasePage.RedirectWithMessage(AdminDefaultPage, "您没有访问当前页面的权限,请与系统管理员联系!");
				return;
			}

			string MID = Request.QueryString["mid"];
			string CID = Request.QueryString["cid"];
			this.HidMID.Value = MID;
			this.HidCID.Value = CID;
			#region CouncliName
			if (string.IsNullOrWhiteSpace(CID))
			{
				Expression<Func<TB_CouncilInfo, bool>> f = (p => p.Status);
				var result_c = DAL.DALHelper.Instance.GetFirstOrDefaultObject<TB_CouncilInfo>(f);
				this.ConTitle = "内容编辑：会员单位";
			}
			else
			{
				int Cid = Convert.ToInt32(CID);
				var result_c = DAL.DALHelper.Instance.GetObject<TB_CouncilInfo>("Index", Cid);
				this.ConTitle = "内容编辑：会员关系";
			}
			#endregion

			if (!IsPostBack)
			{
				ShowMemberCon(MID, CID);
			}
		}

		protected void ShowMemberCon(string MID, string CID)
		{
			int Mid = 0;
			int Cid = 0;

			if (!int.TryParse(CID, out Cid) && !int.TryParse(MID, out Mid))
			{
				this.ClsM.Visible = false;
				return;
			}

			if (!int.TryParse(MID, out Mid))
			{
			}

			TB_Member result = DAL.DALHelper.Instance.GetObject<TB_Member>("ID", Mid);

			this.Mname.Text = result.Name;
			this.MTel.Text = result.Telephone;
			this.MFax.Text = result.Fax;
			this.MEmail.Text = result.EMail;
			this.MWeb.Text = result.WebSite;
			this.Madd.Text = result.Address;
			this.EMname.Text = result.EnName;
			this.EMadd.Text = result.EnAddress;
			this.EMPer.Text = result.ContractPersonEnName;
			this.MPer.Text = result.ContractPersonName;



			if (!int.TryParse(CID, out Cid) && int.TryParse(MID, out Mid))
			{// 会员单位
				this.Url = result.LogoUrl;
				this.linkView.Attributes.Add("href", this.Url);
				this.ClsM.Visible = false;
			}
			if (int.TryParse(CID, out Cid) && int.TryParse(MID, out Mid))
			{// 理事会
				//this.Mname.r
				this.Url = "javascript:void(0)";
				this.linkView.Attributes.Add("href", this.Url);
				this.Mname.Attributes.Add("disabled", "true");
				this.MTel.Attributes.Add("disabled", "true");
				this.MFax.Attributes.Add("disabled", "true");
				this.MEmail.Attributes.Add("disabled", "true");
				this.MWeb.Attributes.Add("disabled", "true");
				this.Madd.Attributes.Add("disabled", "true");
				this.EMname.Attributes.Add("disabled", "true");
				this.EMadd.Attributes.Add("disabled", "true");
				this.EMPer.Attributes.Add("disabled", "true");
				this.MPer.Attributes.Add("disabled", "true");
				this.MLogo.Attributes.Add("disabled", "true");
				this.linkView.Attributes.Add("disabled", "true");
				//this.MLogo. = true;
				Expression<Func<View_CinfoRelationMember, bool>> F = (p => p.MID == Mid && p.Index == Cid);
				var resultV = DAL.DALHelper.Instance.GetFirstOrDefaultObject<View_CinfoRelationMember>(F);
				if (resultV != null)
				{
					DropDownListMClass(resultV.Type);
				}
			}
		}

		protected void DropDownListMClass(string Sel)
		{
			var result = SystemMapCache.Instance.List.Where(c => c.Code.StartsWith("000100050")).ToList();
			this.MClass.AppendDataBoundItems = true;
			this.MClass.DataSource = result;
			this.MClass.DataTextField = "CText";
			this.MClass.DataValueField = "Code";
			DataBind();
			if (Sel != "")
				this.MClass.SelectedIndex = this.MClass.Items.IndexOf(this.MClass.Items.FindByValue(Sel));

		}

		protected void SubBtn_Click(object sender, EventArgs e)
		{
			string CID = this.HidCID.Value;
			string MID = this.HidMID.Value;

			if (string.IsNullOrWhiteSpace(CID))
			{
				MemberInto(MID);
			}
			else
			{
				CouncilInto(MID, CID);
			}
		}

		// 理事会 会员关系
		protected void CouncilInto(string MID, string CID)
		{
			int Mid = 0;
			int Cid = 0;
			if (Int32.TryParse(MID, out Mid) && Int32.TryParse(CID, out Cid))
			{
				Expression<Func<TB_CouncilRelation, bool>> F = (p => p.MemberID == Mid && p.Index == Cid);
				var resultCR = DAL.DALHelper.Instance.GetFirstOrDefaultObject<TB_CouncilRelation>(F);

				resultCR.Type = this.MClass.SelectedValue;
				DAL.DALHelper.Instance.Update<TB_CouncilRelation>(resultCR);
				DAL.DALHelper.Instance.SaveChanges();

				BasePage.CloseWindow(true);
			}
			else
			{
				ClientScript.RegisterClientScriptBlock(this.GetType(), "AlertMsg", "<script type='text/javascript'>alert('页面加载有错误，请注销重新登入后编辑！');window.close();</script>");
				return;
			}
		}

		//  会员
		protected void MemberInto(string MID)
		{
			if (string.IsNullOrWhiteSpace(MID))
			{//Creat 检查是否存在
				if (MemberCheck(this.Mname.Text))
				{
					TB_Member NewObj = DAL.DALHelper.Instance.Create<TB_Member>();
					// 上传文件
					string LogoUrl;
					if (MLogo.HasFile)
					{
						LogoUrl = BasePage.UploadFile(this.MapCode, this.MLogo.FileName, this.MLogo.FileBytes);

					}
					else
					{
						LogoUrl = string.Empty;
					}

					NewObj.Name = this.Mname.Text;
					NewObj.Telephone = this.MTel.Text;
					NewObj.Fax = this.MFax.Text;
					NewObj.EMail = this.MEmail.Text;
					NewObj.WebSite = this.MWeb.Text;
					NewObj.Address = this.Madd.Text;
					NewObj.LogoUrl = LogoUrl;
					NewObj.ContractPersonName = this.MPer.Text;
					NewObj.EnName = this.EMname.Text;
					NewObj.EnAddress = this.EMadd.Text;
					NewObj.ContractPersonEnName = this.EMPer.Text;
					NewObj.Status = true;
					DAL.DALHelper.Instance.Add<TB_Member>(NewObj);
					DAL.DALHelper.Instance.SaveChanges();

					if (MLogo.HasFile)
					{
						// 新增记录ID
						int MemberID = NewObj.ID;
						UploadFile(MemberID, LogoUrl);
					}
				}
				else
				{
					ClientScript.RegisterClientScriptBlock(this.GetType(), "AlertMsg", "<script type='text/javascript'>alert('此会员单位已存在！');location=location;</script>");
					return;
				}
			}
			else
			{// Insert
				TB_Member result_m = DAL.DALHelper.Instance.GetObject<TB_Member>("ID", Convert.ToInt32(MID));
				if (result_m != null)
				{
					result_m.Name = this.Mname.Text;
					result_m.Telephone = this.MTel.Text;
					result_m.Fax = this.MFax.Text;
					result_m.EMail = this.MEmail.Text;
					result_m.WebSite = this.MWeb.Text;
					result_m.Address = this.Madd.Text;
					result_m.EnName = this.EMname.Text;
					result_m.EnAddress = this.EMadd.Text;
					result_m.ContractPersonEnName = this.EMPer.Text;
					if (MLogo.HasFile)
					{
						string LogoUrl = BasePage.UploadFile(this.MapCode, this.MLogo.FileName, this.MLogo.FileBytes);
						result_m.LogoUrl = LogoUrl;
						UploadFile(Convert.ToInt32(MID), LogoUrl);
					}
					result_m.ContractPersonName = this.MPer.Text;

					DAL.DALHelper.Instance.Update<TB_Member>(result_m);
					DAL.DALHelper.Instance.SaveChanges();
				}
				else
				{
					ClientScript.RegisterClientScriptBlock(this.GetType(), "AlertMsg", "<script type='text/javascript'>alert('页面加载有错误，请注销重新登入后编辑！');window.close();</script>");
					return;
				}
			}
			RefreshNewsList();
		}

		protected bool MemberCheck(string Name)
		{
			Expression<Func<TB_Member, bool>> f = (p => p.Name == Name);
			var resultN = DAL.DALHelper.Instance.GetFirstOrDefaultObject<TB_Member>(f);
			if (resultN != null)
			{
				this.MsgMname.Text = "单位名称已存在。";
				return false;
			}
			return true;
		}

		protected void UploadFile(int Mid, string LogoUrl)
		{
			TB_UploadInfo upload = DAL.DALHelper.Instance.Create<TB_UploadInfo>();
			upload.CreateBy = AdminBasePage.AdminInfo.UserName;
			upload.CreateDate = DateTime.Now;
			upload.FilePath = LogoUrl;
			upload.FileType = BasePage.GetFileExt(this.MLogo.FileName);
			upload.Name = "会员单位Logo";
			upload.PrimaryID = Mid;
			upload.Type = this.MapCode;
			DAL.DALHelper.Instance.Add<TB_UploadInfo>(upload);
			DAL.DALHelper.Instance.SaveChanges();

		}


		private void RefreshNewsList()
		{
			string clientJs = "<script type=\"text/javascript\" language=\"javascript\">";
			clientJs += "if(window.opener && window.opener.RefreshNewsList) window.opener.RefreshNewsList();";
			clientJs += "window.close();</script>";
			Response.Write(clientJs);
			Response.End();
		}
	}
}